package com.saohuobang.test.service.impl;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.jmx.JMXConfigurator;
import com.google.common.base.Strings;
import com.saohuobang.test.service.JMXConfigService;
import com.sun.jdmk.comm.HtmlAdaptorServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.management.*;

/**
 * 作者 yaohua.liu
 * 日期 2015-11-25 14:23
 * 包名 com.saohuobang.test.service.impl
 * 说明 ...
 */
@Service("jMXConfigService")
public class JMXConfigServiceImpl implements JMXConfigService {

    private Logger logger = LoggerFactory.getLogger(JMXConfigService.class);

    public final String DOMAIN_NAME = "logback_jmx";
    public final String RELOAD_CONFIG_NAME = "reloadConfig";
    public final String CONNECTOR_NAME = "htmlConnector";
    private MBeanServer mBeanServer;
    private JMXConfigurator reloadConfig;
    private HtmlAdaptorServer connector;
    public LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    private int defaultPort = 10110;

    @Override
    public String startJMXConfig(String portStr) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException {
        mBeanServer = MBeanServerFactory.createMBeanServer(DOMAIN_NAME);

        int port = 0;
        try {
            if (Strings.isNullOrEmpty(portStr)) {
                port = defaultPort;
            } else {
                port = Integer.parseInt(portStr);
            }
        } catch (Exception e) {
            logger.error("格式化JMX端口：{}失败,使用默认端口：{}", portStr, defaultPort);
            port = defaultPort;
        }
        // 注册服务
        ObjectName on = new ObjectName(DOMAIN_NAME + ":name=" + RELOAD_CONFIG_NAME);
        reloadConfig = new JMXConfigurator(loggerContext, mBeanServer, on);
        mBeanServer.registerMBean(reloadConfig, new ObjectName(DOMAIN_NAME + ":name=" + RELOAD_CONFIG_NAME));
        // 注册连接
        connector = new HtmlAdaptorServer();
        connector.setPort(port);
        mBeanServer.registerMBean(connector, new ObjectName(DOMAIN_NAME + ":name=" + CONNECTOR_NAME));

        connector.start();

        return DOMAIN_NAME + ":" + port;
    }

    @Override
    public String stopJMXConfig() throws Exception {
        if (connector != null && connector.isActive()) {
            connector.stop();
        }

        mBeanServer = null;
        reloadConfig = null;
        connector = null;

        return "stop success!";
    }
}
